#include <iostream>
using namespace std;
#include <new>

const int BUF = 512;
const int N = 5;
char buffer[BUF];

int main() {
  double *pd1, *pd2;
  int i;
  cout << "Calling new and placement nwe:" << endl;
  pd1 = new double[N];
  pd2 = new (buffer) double
      [N]; // pd2将开辟N个空间，但是从buffer中开辟，这里指定了开辟空间的位置
  for (int i = 0; i < N; i++) {
    pd2[i] = pd1[i] = 1000 + 20 * i;
  }
  cout << "Buffer address:" << endl;
  cout << "heap :" << pd1 << "ststic:" << (void *)buffer << endl;
  cout << "Buffer content:" << endl;
  for (int i = 0; i < N; i++) {
    cout << pd1[i] << " at " << &pd1[i] << ";";
    cout << pd2[i] << " at " << &pd2[i] << endl;
  }

  double *pd3, *pd4;
  cout << "Calling new and placement nwe:" << endl;
  pd3 = new double[N];
  pd4 = new (buffer) double
      [N]; // pd2将开辟N个空间，但是从buffer中开辟，这里指定了开辟空间的位置
  for (int i = 0; i < N; i++) {
    pd4[i] = pd3[i] = 1000 + 20 * i;
  }
  cout << "Buffer content:" << endl;
  for (int i = 0; i < N; i++) {
    cout << pd3[i] << " at " << &pd3[i] << ";";
    cout << pd4[i] << " at " << &pd4[i] << endl;
  }
  delete[] pd1;
  pd1 = new double[N];
  pd2 = new (buffer + N * sizeof(double)) double[N];
  for (int i = 0; i < N; i++) {
    pd2[i] = pd1[i] = 1000 + 20 * i;
  }

  cout << "Buffer content:" << endl;
  for (int i = 0; i < N; i++) {
    cout << pd1[i] << " at " << &pd1[i] << ";";
    cout << pd2[i] << " at " << &pd2[i] << endl;
  }
  delete[] pd1;
  delete[] pd3;

  return 0;
}
